<?php

namespace App\Http\Middleware;

use App\Models\Park\ParkGate;
use Closure;

class ParkAuth
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $data = $request->input();

        try {
            $this->verifySign($data);
        } catch (\Exception $e) {
            return Response()->json([
                'success' => false,
                'message' => $e->getMessage(),
                'code' => '',
            ], 200);
        }

        return $next($request);
    }

    // 获取sign
    function getSign($token, $data)
    {
        $row = $data;

        unset($data['timestamp'], $data['sign']);
        $str = '';

        foreach ($data as $k => $v){
            $str = (empty($str) ? '' : '#') . $k;
        }

        $str .= '#'.$row['timestamp'];
        $str .= '#'.$token;
        // 生成sign
        $sign = md5($str);

        return $sign;
    }

    //延签
    function verifySign($data)
    {
        try {
            // 验证参数中是否有签名
            if (!isset($data['sign']) || !$data['sign']) throw new \Exception('发送的数据签名不存在');
            if (!isset($data['timestamp']) || !$data['timestamp']) throw new \Exception('发送的数据参数不合法');
            if (!isset($data['park_gate_id']) || !$data['park_gate_id']) throw new \Exception('停车场id不存在');

            $parkGate = ParkGate::find($data['park_gate_id']);
            if(empty($parkGate))  throw new \Exception('停车场不存在');

            $sign2 = $this->getSign($parkGate->token, $data);

            if ($data['sign'] != $sign2) throw new \Exception('签名错误');

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}
